<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">

  </forms>
</template>

<script>
import {camel_str} from "@/js/s94_tool.js";
import s94Mjs from "s94-js";
import {href_handle, iframe} from "@/js/tool.js";
import {ajax} from "@/js/api_tool.js";
import {S94Model} from "@/js/S94Model.js";

export default {
  props: {
    __iframe: Object,
    model: S94Model,
    this_action: Object,
  },
  data(){
    let id = this.$get('id'), btns = undefined;
    let change_need_init = this.this_action.init_need_param ? s94Mjs.to_string(this.this_action.init_need_param).split(",") : [];
    return {
      id: id,
      btns: btns,
      config: {},
      change_need_init: change_need_init,
    }
  },
  methods: {
    url(init){
      let param = {};
      if (init) param._is_init_ = 1;
      if (this.id) param.id = this.id;
      let param_str = s94Mjs.param_encode(param);
      return `/admin/${this.model.name}/${this.this_action.action}?${param_str}`
    },
    param(data){
      data = data || {};
      data.model_name = this.model.name;
      return s94Mjs.param_encode(data);
    },
    onsubmit(formData){
      ajax({url:this.url(), method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('model_v2_base/index?'+this.param(), '$refs.list_url.list');
          iframe.hide('model_v2_base/edit?'+this.param());
          if (!this.id) this.$refs['forms'].init();
        }else {
          href_handle('model_v2_base/index?'+this.param());
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    change_after_init(){
      let param = {};
      this.change_need_init.forEach((k)=>{
        param[k] = this.config[k].value;
      })
      this.init(param);
    },
    init(param){
      let is_first = !param;
      let is_info = this.$get('is_info');
      ajax({url:this.url(true), data:param}, (res)=>{
        // 参数解析
        Object.keys(this.config).forEach((k)=>{ this.config[k].remove = true; })
        res.data.forEach((v)=>{
          let old = this.config[v.name] || {};
          v.is_info = (v.can_edit!=1 || !!is_info);
          v.remove = false;
          this.config[v.name] = Object.assign(old, v);
        })

        if (is_first){
          if (is_info) this.btns = [];
          // 变动后需要初始化的参数处理
          Object.keys(this.config).forEach(name=>{
            if (~this.change_need_init.indexOf(name)) {
              this.config[name].onchange = this.change_after_init;
            }
          })
        }
        return false;
      })
    },
  },
  computed: {
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (!app.model.name){
      return this.__iframe ? iframe.hide('model_v2_base/edit') : href_handle(-1);
    }
    //其他初始化操作
    this.init();
  }
}
</script>
